<?php
session_start();
/* SESSION VARIABLE USAGE:
array(<name>      => <values>    description
      'username'  => [string]    the unique username used to authenticate to the application
      'logged_in' => TRUE/FALSE  true if the current user has been authenticated)
      'token'     => [string]    a username-unique auth token returned by the backend upon login. Used to sequester multi-tenant data.)
     )
*/

// More notes:
//     * The functions prefixed with "sclm_" are xajax callback functions.
//     
//     
//     
//     

require_once('xajax/xajax_core/xajaxAIO.inc.php');
require_once('sclm_api/api.php');

function sclm_renderLogin($form, $include) {
    $response = new xajaxResponse();
    $response->assign('body', 'innerHTML', "FIXME!!!<br />This needs to display a login form.");
// FIXME - hack until we have a working login form
$_SESSION['logged_in'] = true;
    //$response->script("alert('Logged in...');");
    return($response);
}




function sclm_logout($form, $include) {
    $response = new xajaxResponse();
    $_SESSION['logged_in'] = FALSE;
    session_destroy();
    $response->assign('body', 'innerHTML', "Please wait, logging out...");
    //reload the page
    $response->redirect('', 0);
    return($response);
}



function sclm_renderAddContactList($form, $include) {
    $response = new xajaxResponse();
    if (!$_SESSION['logged_in']) {
        $response->script("alert('Oops! Please login first.');");
        return($response);
    }
    
    // FIXME: If we're editing an existing record, load it via an API call here (I'm assuming it'll be in $record below)
    
    $html = <<<EOL
<form id="main_form" onKeyDown="return ts_form_okd(this, event);" onSubmit="xajax_run('saveContactList', xajax.getFormValues('main_form')); return false;">
    <input type="hidden" name="id" value="{$record['id']}" id="contact_list_id">
    
    <table cellspacing="1" border="0" cellpadding="0" style="padding: 5px 20px; width: 400px;">
        <tr>
            <td align="right" nowrap="true" class="padding">
                List Name
            </td>
            <td align="left" nowrap="true" class="padding">
                <input
                    id="contact_list_name"
                    name="name"
                    alt="Contact list name"
                    value="{$record['name']}"
                    type="text"
                    size="32" maxlength="255"
                    style="width: 210px;"
                >
            </td>
        </tr>
        
        <tr>
            <td align="right" nowrap="true" class="padding">
                Description
            </td>
            <td align="left" nowrap="true" class="padding">
                <input
                    id="contact_list_description"
                    name="description"
                    alt="Contact list description"
                    value="{$record['description']}"
                    type="text"
                    size="32" maxlength="255"
                    style="width: 210px;"
                >
            </td>
        </tr>
        
        <tr>
            <td colspan="2" align="center" nowrap="true" class="padding">
                <span class="buttons">
                    <button id="save_button" class="save" onClick="return this.form.onsubmit();"
                     ><span id="save_button_label">Save</span>
                    </button>
                </span>
            </td>
        </tr>
        
    </table>
</form>
EOL;
    
    // FIXME: If it's an existing list, it's not possible with the API to change the list's name.
    //        therefore, if we're editing an existing list we should disable (or overlay) the name input box so they don't think they can rename it.
    
    $response->assign('body', 'innerHTML', $html);
    //$response->script("alert('Put something here');");
    return($response);
}




function sclm_saveContactList($form, $include) {
    $response = new xajaxResponse();
    if (!$_SESSION['logged_in']) {
        $response->script("alert('Oops! Please login first.');");
        return($response);
    }
    
    // FIXME: Use a real token!!!
    $token = 'asdfsdfgdfgh';
    
    // Save the contact list
    $status = ContactListManager::createList($token, $form['name'], $form['description']);
    
    if ($status) $response->script("alert('Saved!');");
    else $response->script("alert('Oops, you broke it!');");
    return($response);
}




function sclm_renderContactLists($form, $include) {}
function sclm_renderContactList($form, $include) {}
function sclm_renderAddUpdateContact($form, $include) {}
function _renderSearchedContacts($q) {}
function sclm_renderContacts($form, $include) {
    return _renderSearchedContacts('');
}

function sclm_processContactForm($form, $include) {}
function sclm_renderCreateAccount($form, $include) {}






//////////////////////////////////////////////////////////////////////////////
// Xajax Server
// Function:
//     run ($function, [$form_data], [$include_file])
//
// Description:
//     Generic wrapper to handle xajax submits.
//     Makes it simple to run the php function requested from javascript.
//     The function name passed in will have "run_" prefixed to it so that
//     not just any function can be run from the browser, only functions
//     that start with "sclm_".
//
// Input:
//     $window_name   The name of the "window" submitting data
//     $function      The name of a PHP function to pass the $form_data to.
//                    This function must return an xajax response XML.
//                    For security reasons, the actual function
//                    called will be "sclm_{$function}".
//     $form[]        An optional array/string containing the data
//                    to pass into $function.
//                    This will often be generated by using this javascript
//                    xajax call:  xajax.getFormValues('form_id')
//     $include_file  A filename to optionally include before running $function.
//                    This should not include the file extension, we'll assume
//                    it should have .inc.php postpended to it.
//
//////////////////////////////////////////////////////////////////////////////
function run($function, $form='', $include='') {
    // Instantiate the xajaxResponse object
    $response = new xajaxResponse();
    $js = '';
    
    // Prefix function name for security reasons
    $function = 'sclm_' . $function;
    
    // Include a file if we were asked to
    if ($include) {
        $include = "{$include}.inc.php";
        if (is_file($include)) include_once($include);
    }
    
    // If the function exists, run it and return it's output (an xml response)
    if (function_exists($function)) return($function($form, $include));
    
    // Ok, I couldn't find anything to do.. just return an empty XML response
    error_log("DEBUG => run() couldn't find the function: {$function} in file: {$include}");
    
    return($response);
}















/* And so it begins ... */

// If they ARE logged in, fix a few menu items
$onload_js = "";
if ($_SESSION['logged_in']) {
    $onload_js = <<<EOL
    removeElement('log_in_link');
    removeElement('create_account_link');
EOL;
}
// They're NOT logged in
else {
    $onload_js = <<<EOL
    removeElement('log_out_link');
    removeElement('my_contacts_link');
    removeElement('add_contact_link');
    removeElement('my_lists_link');
    removeElement('add_new_list_link');
    removeElement('my_account_link');
EOL;
}


$xajax = new xajax();
$xajax->configure('debug', false);
$xajax->registerFunction('run');
$xajax->processRequest();
include_once('template-index.html');



/* NOTES about the UI

My Contacts (list of all)
-> Search box (simple, builds a query for them based on First/Last name fields) ... Advanced (lets user enter a query directly)
-> Add new Contact (new page or js popup)
-> per Contact, "Update" button, checkbox [] Selects for bulk update
  -> Then, at bottom, radio buttons for: () Delete Selected, () Add Selected to List [dropdown of list names]

My Lists (list of all list names, maybe first 5-10 contact names..?)
Click a list name, and a new page loads, listing all contact in the list, along with:
  -> Per-Contact checkboxes to select Contacts for removal
  -> Per-Contact "Edit this Contact" button
-> Add new List (name)


CREATING USERS:
Register():
    - desired username (backend should return errors: non-unique username or invalid email address) (PP: this should be an email address)
    - password (sha1 hash + salt)
Login():
    - username (string)
    - password (string)
    Backend returns 1 (int) or TRUE (bool) on successful authentication. Anything else indicates failure.
*/

?>